package cn.edu.fzu.homemaking.chat.config;

import cn.edu.fzu.homemaking.common.SessionConstant;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
@ComponentScan(basePackages = "cn.edu.fzu.homemaking")
public class ChatConfig {

    public static final String EXCHANGE_TOPICS_CHAT = "exchange_topics_chat";

    public static final String QUEUE_CHAT_MESSAGE   = "queue_chat_message";

    public static final String ROUTING_CHAT_MESSAGE = "inform.#.chat.message.#";

    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     **/
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }


    @Bean
    public Docket webApi() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("cn.edu.fzu.homemaking.chat.controller"))
                .paths(PathSelectors.ant("/api/**")).build().groupName("家政系统接口文档V1.0").pathMapping("/").enable(true)
                .apiInfo(new ApiInfoBuilder().title("聊天室接口文档V1.0").description("聊天室模块相关接口").version("1.0").build());
    }


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {

        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();

                if (requestAttributes != null) {
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    //2、同步请求头的数据（主要是cookie）
                    //把老请求的cookie值放到新请求上来，进行一个同步
                    String cookie = request.getHeader("Cookie");
                    if (StringUtils.isBlank(cookie) || !cookie.contains(SessionConstant.DSESSIONID)) {
                        cookie = SessionConstant.DSESSIONID + "=" + request.getSession().getId();
                    }
                    template.header("Cookie", cookie);
                }
            }
        };
    }


    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2处理ie浏览器保存数据时出现下载json数据问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.TEXT_PLAIN);
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        //3.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }


    /** 声明交换机 **/
    @Bean(EXCHANGE_TOPICS_CHAT)
    public Exchange EXCHANGE_TOPICS_INFORM() {
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_CHAT).durable(true).build();
    }


    /** 声明队列 **/
    @Bean(QUEUE_CHAT_MESSAGE)
    public Queue chatMessage() {
        return new Queue(QUEUE_CHAT_MESSAGE);
    }


    @Bean
    public Binding BINDING_QUEUE_INFORM_CHAT(@Qualifier(QUEUE_CHAT_MESSAGE) Queue queue,
                                             @Qualifier(EXCHANGE_TOPICS_CHAT) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_CHAT_MESSAGE).noargs();
    }

}
